<?php

require_once 'control/interface.php';

use control\interfaces;

class doClass
{
    use interfaces;

    public string $date;
    public string $time;

    /**
     * 执行
     */

    public function __construct()
    {
        $this->date = date('Y-m-d');
        $this->time = date('Y-m-d H:i:s');
        $this->formal();          //转正
        $this->jobChange();       //调岗
        $this->certEnd();         //证件到期提醒
        $this->operateCredentialsEnd();         //个人证件到期提醒
        $this->paperTest();       //考试提醒
        $this->deleteEmptyFile(); //删除未使用的文件
        $this->sendVisitMessage();//访客计划发送消息
        $this->recycleClient();   //回收客户和线索
        $this->carWarn();         //车辆年审，保养，保险到期提醒
        $this->staffContract();//员工合同到期处理
        $this->saleOrderWarning();//销售订单交期预警
        $this->purchaseOrderWarning();//采购订单交期预警
        $this->inspectionMaintenance();//设备巡检保养提醒
        $this->overdueReceivableAlert();//超期应收预警
        $this->overduePayableAlert();//超期应付预警
    }


    /**
     * Desc : //定义目录路径
    $file = './control/';
    //执行方法
    echo $this->getFilesNumber($file) . "\n";
     * User : you name
     * Date : 2024-06-21 10:43
     * @param $file
     * @return int|string
     */
    private function getFilesNumber($file)
    {
        // 定义行数
        $number = 0;
        // 判断路径文件是否是一个目录
        if (is_dir($file)) {
            // 返回指定目录中的文件和目录的数组
            $fileArr = scandir($file);
            // 循环返回的目录数组
            foreach ($fileArr as $fileName) {
                // 跳过 . 和 .. 目录
                if ($fileName == '.' || $fileName == '..') continue;
                // 拼接上完整的路径
                $filePath = $file . DIRECTORY_SEPARATOR . $fileName;
                // 判断路径文件是否是一个目录
                if (is_dir($filePath)) {
                    // 如果是一个目录，则再次调用当前方法
                    $number += $this->getFilesNumber($filePath);
                } else {
                    // 获取文件扩展名
                    $extension = pathinfo($filePath, PATHINFO_EXTENSION);
                    // 读取对应类型的文件
                    if (in_array($extension, ['php', 'html', 'js', 'css'])) {
                        // 使用文件行数计数器
                        $fileHandle = fopen($filePath, "r");
                        if ($fileHandle) {
                            while (!feof($fileHandle)) {
                                fgets($fileHandle);
                                $number++;
                            }
                            fclose($fileHandle);
                        }
                    }
                }
            }
        } else {
            // 目录不存在，返回信息
            return '目录不存在，请检查目录路径或名称是否正确！';
        }
        return $number;
    }

    private function staffContract()
    {
        $reminder_settings = query('reminder_settings', "id = 'laborContract'");
        if (!empty($reminder_settings['id'])) {
            $warnDay = $reminder_settings['threshold'];
            $result = find(array('table' => 'staff_contract', 'where' => " isClose=0 and workFlow = '生效中' and DATEDIFF(signEndDate,DATE_FORMAT(now(),'%Y-%m-%d')) = '$warnDay'"));
            if (is_array($result['array'])) {
                foreach ($result['array'] as $array) {
                    $people = array_filter(explode(';', $reminder_settings['selector']));
                    foreach ($people as $stid) {
                        if (self::total(array('table' => 'message', 'where' => " and stid = '$stid' and date(time) = '{$this->date}' and typeId = '{$array['id']}'")) <= 0) {
                            //给提醒人发消息
                            message(array(
                                'stid' => $stid,
                                'type' => '劳动合同到期提醒',
                                'typeId' => $array['id'],
                                'text' => "员工【" . self::findStaff($array['staffId']) . "】的劳动合同即将到期，到期时间【{$array['endDate']}】",
                                'targetCla' => 'workContract',
                                'targetFun' => 'detail',
                            ));
                        }
                    }
                }
            }
        }
        $result = find(array('table' => 'staff_contract', 'where' => " workFlow = '生效中' and signEndDate<DATE_FORMAT(now(),'%Y-%m-%d')"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                update(array(
                    'table' => 'staff_contract',
                    'field' => [
                        'workFlow' => '已终止',
                        'stopDate' => $this->date
                    ],
                    'where' => "id = '$array[id]'"
                ));
            }
        }
    }

    /**
     * 车辆年审，保养，保险到期提醒
     */
    private function carWarn()
    {
        $carWarn = para('carWarn');
        //保险
        $result = find(array('table' => 'car_insure', 'where' => " isWarn=0 and DATEDIFF(endDate,DATE_FORMAT(now(),'%Y-%m-%d')) = '$carWarn'"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $car = query('car', "id = '$array[carId]'");
                if (self::total(array('table' => 'message', 'where' => " and stid = '$car[managerId]' and date(time) = '{$this->date}' and typeId = '{$array['id']}'")) <= 0) {
                    //给提醒人发消息
                    message(array(
                        'stid' => $car['managerId'],
                        'type' => '车辆提醒',
                        'typeId' => $array['id'],
                        'text' => "车辆【{$array['shortName']}{$array['carNo']}】-【{$array['brand']}】保险即将到期，到期时间【{$array['endDate']}】",
                        'targetCla' => 'car',
                        'targetFun' => 'detail',
                    ));
                    update(array(
                        'table' => 'car_insure',
                        'field' => ['isWarn' => 1],
                        'where' => "id = '$array[id]'",
                    ));
                }
            }
        }
        //保养
        $result = find(array('table' => 'car_maintainance', 'where' => " isWarn=0 and DATEDIFF(nextDate,DATE_FORMAT(now(),'%Y-%m-%d')) = '$carWarn'"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $car = query('car', "id = '$array[carId]'");
                if (self::total(array('table' => 'message', 'where' => " and stid = '$car[managerId]' and date(time) = '{$this->date}' and typeId = '{$array['id']}'")) <= 0) {
                    $car = query('car', "id = '$array[carId]'");
                    //给提醒人发消息
                    message(array(
                        'stid' => $car['managerId'],
                        'type' => '车辆提醒',
                        'typeId' => $array['id'],
                        'text' => "车辆【{$array['shortName']}{$array['carNo']}】-【{$array['brand']}】即将到保养日期，下次保养日期为【{$array['nextDate']}】",
                        'targetCla' => 'car',
                        'targetFun' => 'detail',
                    ));
                    update(array(
                        'table' => 'car_maintainance',
                        'field' => ['isWarn' => 1],
                        'where' => "id = '$array[id]'",
                    ));
                }
            }
        }
        //年审
        $result = find(array('table' => 'car_inspection', 'where' => " isWarn=0 and DATEDIFF(endDate,DATE_FORMAT(now(),'%Y-%m-%d')) = '$carWarn'"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $car = query('car', "id = '$array[carId]'");
                if (self::total(array('table' => 'message', 'where' => " and stid = '$array[managerId]' and date(time) = '{$this->date}' and typeId = '{$array['id']}'")) <= 0) {
                    //给提醒人发消息
                    message(array(
                        'stid' => $car['managerId'],
                        'type' => '车辆提醒',
                        'typeId' => $array['id'],
                        'text' => "车辆【{$array['shortName']}{$array['carNo']}】-【{$array['brand']}】即将到年审结束日期，到期时间【{$array['endDate']}】",
                        'targetCla' => 'car',
                        'targetFun' => 'detail',
                    ));
                    update(array(
                        'table' => 'car_inspection',
                        'field' => ['isWarn' => 1],
                        'where' => "id = '$array[id]'",
                    ));
                }
            }
        }
    }

    /**
     * 回收客户和线索
     */

    private function recycleClient()
    {
        //分配时效回收 >=
        $result = find(array('table' => 'kehu as a join pool as b on a.poolId = b.id', 'field' => "a.*", 'where' => " a.manager !='' and a.data_source = 0 and b.limitMinute>0 and disTime is not null and lastFollowTime is null and UNIX_TIMESTAMP(disTime)+60*b.limitMinute <= UNIX_TIMESTAMP()"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                static::update(array('table' => 'kehu', 'field' => ['manager' => '', 'collaborator' => '', 'see' => '', 'disTime' => '', 'lastFollowTime' => ''], 'where' => "khid = '$array[khid]'"));
            }
        }
        //多少天内无跟进自动回收 >=
        $result = find(array('table' => 'kehu as a join pool as b on a.poolId = b.id', 'field' => "a.*", 'where' => " a.manager !='' and a.data_source = 0 and b.recycling>0 and disTime is not null and lastFollowTime is not null and DATEDIFF(DATE_FORMAT(now(),'%Y-%m-%d'),lastFollowTime) >=b.recycling"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                static::update(array('table' => 'kehu', 'field' => ['manager' => '', 'collaborator' => '', 'see' => '', 'disTime' => '', 'lastFollowTime' => ''], 'where' => "khid = '$array[khid]'"));
            }
        }

        //提前提醒
        $result = find(array('table' => 'kehu as a join pool as b on a.poolId = b.id', 'field' => "a.*,b.remindDay", 'where' => " a.manager !='' and a.data_source = 0 and b.recycling>0 and b.remindDay >0 and disTime is not null and lastFollowTime is not null and (recycling-DATEDIFF(DATE_FORMAT(now(),'%Y-%m-%d'),lastFollowTime)) = b.remindDay"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                if (self::total(array('table' => 'message', 'where' => " and stid = '$array[manager]' and date(time) = '{$this->date}' and type='客户回收提醒' and typeId = '{$array['khid']}'")) <= 0) {
                    $days = self::diffDays($this->time, $array['lastFollowTime']);
                    //未发送的人
                    message(array(
                        "stid" => $array['manager'],
                        "type" => "客户回收提醒",
                        "typeId" => $array['khid'],
                        "text" => "您的客户【{$array['companyName']}】已有{$days}天未跟进，系统将在{$array['remindDay']}天后回收",
                        'targetCla' => 'client',
                        'targetFun' => 'home',
                    ));
                }
            }
        }

        /******回收线索******/
        //分配时效回收 >=
        $result = find(array('table' => 'clue as a join pool as b on a.poolId = b.id', 'field' => "a.*", 'where' => " a.manager !='' and b.limitMinute>0 and disTime is not null and lastFollowTime is null and UNIX_TIMESTAMP(disTime)+60*b.limitMinute <= UNIX_TIMESTAMP()"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                static::update(array('table' => 'clue', 'field' => ['manager' => '', 'collaborator' => '', 'see' => '', 'disTime' => '', 'lastFollowTime' => ''], 'where' => "id = '$array[id]'"));
            }
        }
        //多少天内无跟进自动回收 >=
        $result = find(array('table' => 'clue as a join pool as b on a.poolId = b.id', 'field' => "a.*", 'where' => " a.manager !='' and b.recycling>0 and disTime is not null and lastFollowTime is not null and DATEDIFF(DATE_FORMAT(now(),'%Y-%m-%d'),lastFollowTime) >=b.recycling"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                static::update(array('table' => 'clue', 'field' => ['manager' => '', 'collaborator' => '', 'see' => '', 'disTime' => '', 'lastFollowTime' => ''], 'where' => "id = '$array[id]'"));
            }
        }
        //提前提醒
        $result = find(array('table' => 'clue as a join pool as b on a.poolId = b.id', 'field' => "a.*,b.remindDay", 'where' => " a.manager !='' and b.recycling>0 and b.remindDay >0 and disTime is not null and lastFollowTime is not null and (recycling-DATEDIFF(DATE_FORMAT(now(),'%Y-%m-%d'),lastFollowTime)) = b.remindDay"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                if (self::total(array('table' => 'message', 'where' => " and stid = '$array[manager]' and date(time) = '{$this->date}' and type='线索回收提醒' and typeId = '{$array['id']}'")) <= 0) {
                    $days = self::diffDays($this->time, $array['lastFollowTime']);
                    //未发送的人
                    message(array(
                        "stid" => $array['manager'],
                        "type" => "线索回收提醒",
                        "typeId" => $array['id'],
                        "text" => "您的线索【{$array['name']}】已有{$days}天未跟进，系统将在{$array['remindDay']}天后回收",
                        'targetCla' => 'clue',
                        'targetFun' => 'home',
                    ));
                }
            }
        }
    }

    /**
     * 访客计划发送消息
     */
    private function sendVisitMessage()
    {
        $result = find(array('table' => 'visit_plan', 'where' => " date(startRemindTime) = '{$this->date}' and UNIX_TIMESTAMP(startRemindTime)>0 and UNIX_TIMESTAMP(startRemindTime) <= UNIX_TIMESTAMP()"));
        foreach ($result['array'] as $array) {
            if (self::total(array('table' => 'message', 'where' => " and stid = '$array[stid]' and date(time) = '{$this->date}' and type='访客计划' and typeId = '{$array['id']}'")) <= 0) {
                //未发送销售的人
                message(array(
                    "stid" => $array['stid'],
                    "type" => "访客计划",
                    "typeId" => $array['id'],
                    "text" => "您有一条日程【{$array['theme']}】在【{$array['startTime']}】开始",
                    'targetCla' => 'visitPlan',
                    'targetFun' => 'home',
                ));
            }
        }
    }

    /**
     * 删除超过一天的未使用文件
     */
    public function deleteEmptyFile()
    {
        $result = find(array('table' => 'file', 'where' => " targetId= '' and DATEDIFF(DATE_FORMAT(now(),'%Y-%m-%d'),time) >1"));
        foreach ($result['array'] as $array) {
            fileDelete($array['src']);
            delete(array('table' => 'file', 'where' => " id = '$array[id]'"));
        }
    }

    /**
     * 考试提醒
     */
    private function paperTest()
    {
        $result = find(array('table' => 'paper_library', 'where' => " isMessage= 0 and state = '已发布' and UNIX_TIMESTAMP(startTime) <= UNIX_TIMESTAMP() and UNIX_TIMESTAMP(endTime) >= UNIX_TIMESTAMP()"));
        foreach ($result['array'] as $array) {
            $member = explode(',', $array['member']);
            if (is_array($member)) {
                foreach ($member as $stid) {
                    if (self::total(array('table' => 'message', 'where' => " and stid = '$stid' and type='考试试卷' and typeId = '{$array['id']}'")) <= 0) {
                        //未发送的人
                        message(array(
                            "stid" => $stid,
                            "type" => "考试试卷",
                            "typeId" => $array['id'],
                            "text" => "您有一张考试试卷【{$array['name']}】需要作答",
                            'targetCla' => 'beTested',
                            'targetFun' => 'home',
                        ));
                    }
                }
            }
            //更新为已发送提醒消息
            update(array('table' => 'paper_library', 'field' => ['isMessage' => 1], 'where' => " id = '$array[id]'"));
        }
    }

    /**
     * 一天一次
     * 证件到期提醒
     */
    public function certEnd()
    {
        $result = find(array('table' => 'certificate', 'where' => "isLong =0 and limitDay>0 and DATEDIFF(auditDate,DATE_FORMAT(now(),'%Y-%m-%d')) = limitDay and remindStid !=''"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                if (self::total(array('table' => 'message', 'where' => " and stid = '$array[remindStid]' and date(time) = '{$this->date}' and typeId = '{$array['id']}'")) <= 0) {
                    //给提醒人发消息
                    message(array(
                        'stid' => $array['remindStid'],
                        'type' => '证件到期提醒',
                        'typeId' => $array['id'],
                        'text' => "证件【{$array['type']}】-【{$array['name']}】即将到期，审核时间【{$array['auditDate']}】",
                        'targetCla' => 'certificate',
                        'targetFun' => 'detail',
                    ));
                }
            }
        }
    }

    /**
     * 一天一次
     * 员工证件到期提醒
     */
    public function operateCredentialsEnd()
    {
        $result = find(array('table' => 'operate_credentials', 'where' => "isLong =0 and limitDay>0 and DATEDIFF(auditDate,DATE_FORMAT(now(),'%Y-%m-%d')) = limitDay and remindStid !=''"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                if (self::total(array('table' => 'message', 'where' => " and stid = '$array[remindStid]' and date(time) = '{$this->date}' and typeId = '{$array['id']}'")) <= 0) {
                    //给提醒人发消息
                    message(array(
                        'stid' => $array['remindStid'],
                        'type' => '证件到期提醒',
                        'typeId' => $array['id'],
                        'text' => "证件【{$array['type']}】-【{$array['name']}】即将到期，审核时间【{$array['auditDate']}】",
                        'targetCla' => 'certificate',
                        'targetFun' => 'detail',
                    ));
                }
            }
        }
    }

    /**
     * 一天一次
     * 转正
     */
    private function formal()
    {
        $result = find(array('table' => "staff_formal", "where" => " confirmDate is null and formalDate=DATE_FORMAT(now(),'%Y-%m-%d') and state = '已通过'"));
        foreach ($result['array'] as $array) {
            update(array(
                'table' => 'staff_formal',
                'field' => [
                    'confirmDate' => $this->date,
                    'updateTime' => $this->time,
                ],
                'where' => " id = '$array[id]'",
            ));
            update(array(
                'table' => 'staff',
                'field' => [
                    'state' => '转正',
                    'updateTime' => $this->time,
                ],
                'where' => " state = '试用' and stid = '$array[staffId]'",
            ));
            //生成员工变动记录
            $this->insertStaffStateRecord($array['staffId'], '转正', $array['id'], $this->date);
        }
    }

    /**
     * 插入状态变动记录
     * @param $stid string 员工ID
     * @param $type string 变动类型
     * @param $sourceId string 来源ID
     * @param $recordDate string 变动日期
     */
    private function insertStaffStateRecord(string $stid, string $type, string $sourceId, string $recordDate)
    {
        $sourceTable = '';
        if ($type == '入职') {
            $sourceTable = 'staff_entry_record';
        } elseif ($type == '转正') {
            $sourceTable = 'staff_formal';
        } elseif ($type == '调岗') {
            $sourceTable = 'job_apply';
        } elseif ($type == '停薪留职') {
            $sourceTable = 'staff_stay_record';
        } elseif ($type == '离职') {
            $sourceTable = 'staff_quit_record';
        } elseif ($type == '上岗') {
            $sourceTable = 'staff_stay_record';
        }
        $info = query($sourceTable, " id = '$sourceId' order by time desc");
        static::insert(array(
            'table' => 'staff_state_record',
            'field' => [
                'id' => self::getId(),
                'stid' => $stid,
                'name' => self::findStaff($stid),
                'type' => $type,
                'sourceTable' => $sourceTable,
                'sourceId' => $sourceId,
                'orderNo' => $info['orderNo'],
                'recordDate' => $recordDate,
                'time' => $this->time,
            ]
        ));
    }

    /**
     * 一天一次
     *调岗
     */
    private function jobChange()
    {
        $result = find(array('table' => 'job_apply', 'where' => " confirmDate is null and startDate=DATE_FORMAT(now(),'%Y-%m-%d') and state = '已通过'"));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                update(array('table' => 'staff', 'field' => ['jobId' => $array['jobId']], 'where' => " talentId = '$array[talentId]'"));
                //生成员工变动记录
                $this->insertStaffStateRecord($array['staffId'], '调岗', $array['id'], $this->date);
            }
        }
        update(array('table' => 'job_apply', 'field' => array('confirmDate' => $this->date, 'updateTime' => $this->time), 'where' => " confirmDate is null and startDate=DATE_FORMAT(now(),'%Y-%m-%d') and state = '已通过'"));
    }

    /**
     * 批量输出修改语句(自用)
     */
    public function echoSql(): string
    {
        $text = '';
        $sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA ='demo' and TABLE_TYPE = 'BASE TABLE'";
        $all = self::sqlFind($sql);
        foreach ($all as $array) {
            $sql = "SELECT COLUMN_NAME,COLUMN_COMMENT FROM information_schema.columns WHERE TABLE_SCHEMA='demo' AND TABLE_NAME='{$array['TABLE_NAME']}'";
            $result = self::sqlFind($sql);
            $field = [];
            $comment = [];
            foreach ($result as $val) {
                $field[] = $val['COLUMN_NAME'];
                $comment[$val['COLUMN_NAME']] = $val['COLUMN_COMMENT'];
            }
            if (in_array('num', $field, true)) {
                $text .= "ALTER TABLE `{$array['TABLE_NAME']}` CHANGE `num` `num` DECIMAL(15,4) NOT NULL DEFAULT '0.00' COMMENT '数量';<br>";
            }
        }
        return $text;
    }
    public function echoSql1(): string
    {
        $text = '';
        $sql = "SELECT TABLE_NAME FROM information_schema.tables WHERE TABLE_SCHEMA ='demo' and TABLE_TYPE = 'BASE TABLE'";
        $all = self::sqlFind($sql);
        foreach ($all as $array) {
            $sql = "SELECT * FROM information_schema.columns WHERE table_schema = 'demo' AND table_name = '{$array['TABLE_NAME']}' ";
            $result = self::sqlFind($sql);
            foreach ($result as $val) {
                if ($val['COLUMN_TYPE'] =='decimal(12,4)'){
                    $text .= "ALTER TABLE `{$array['TABLE_NAME']}` CHANGE `{$val['COLUMN_NAME']}` `{$val['COLUMN_NAME']}` DECIMAL(20,4) NOT NULL DEFAULT '0.0000' COMMENT '{$val['COLUMN_COMMENT']}';<br>";
                }elseif($val['COLUMN_TYPE'] =='decimal(12,2)'){
                    $text .= "ALTER TABLE `{$array['TABLE_NAME']}` CHANGE `{$val['COLUMN_NAME']}` `{$val['COLUMN_NAME']}` DECIMAL(20,2) NOT NULL DEFAULT '0.00' COMMENT '{$val['COLUMN_COMMENT']}';<br>";
                }
            }
        }
        return $text;
    }

    /**
     *
     * 销售订单交期预警
     */
    public function saleOrderWarning()
    {
        $setting = self::getSettingValue('salesDeliveryAlert');
        $result = find(array('table' => 'sale_order', 'where' => " state = '已确认' and deliveryDate is not null and DATE_SUB(deliveryDate,INTERVAL {$setting['threshold']} DAY) = '{$this->date}' "));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                foreach ($setting['member'] as $item) {
                    if (self::total(array('table' => 'message', 'where' => " and stid = '$item' and date(time) = '{$this->date}' and typeId = '{$array['id']}' and type = '预警消息' ")) <= 0) {
                        //给提醒人发消息
                        message(array(
                            'stid' => $item,
                            'type' => '预警消息',
                            'typeId' => $array['id'],
                            'text' => "请注意！销售订单【{$array['orderNo']}】的交货日期是【{$array['deliveryDate']}】",
                            'targetCla' => 'saleOrder',
                            'targetFun' => 'detail',
                        ));
                    }
                }
            }
        }
    }

    /**
     *
     * 采购订单交期预警
     */
    public function purchaseOrderWarning()
    {
        $setting = self::getSettingValue('purchaseDelivery');
        $result = find(array('table' => 'purchase_order', 'where' => " state = '已确认' and deliveryDate is not null and DATE_SUB(deliveryDate,INTERVAL {$setting['threshold']} DAY) = '{$this->date}' "));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                foreach ($setting['member'] as $item) {
                    if (self::total(array('table' => 'message', 'where' => " and stid = '$item' and date(time) = '{$this->date}' and typeId = '{$array['id']}' and type = '预警消息' ")) <= 0) {
                        //给提醒人发消息
                        message(array(
                            'stid' => $item,
                            'type' => '预警消息',
                            'typeId' => $array['id'],
                            'text' => "请注意！采购订单【{$array['orderNo']}】的交货日期是【{$array['deliveryDate']}】",
                            'targetCla' => 'purchaseOrder',
                            'targetFun' => 'detail',
                        ));
                    }
                }
            }
        }
    }

    /**
     *
     * 巡检/保养计划提醒
     */
    public function inspectionMaintenance()
    {
        $result = find(array('table' => 'equipment_patrol_tpl', 'where' => " type in ('巡检计划','保养计划') and frequency <> '' "));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                $arr = ['巡检计划' => '设备巡检', '保养计划' => '设备保养'];
                $lastData = query('equipment_patrol', " eqid = '$array[eqid]' AND tpid = '$array[id]' and type = '{$arr[$array['type']]}' ORDER BY lastDate DESC ");
                $lastData['lastDate'] = empty($lastData['lastDate']) ? date("Y-m-d", strtotime($array['time'])) : $lastData['lastDate'];
                switch ($array['frequency']) {
                    case '每天':
                        $next = date("Y-m-d", strtotime("+1 days", strtotime($lastData['lastDate'])));
                        break;
                    case '每周':
                        $next = date("Y-m-d", strtotime("+7 days", strtotime($lastData['lastDate'])));
                        break;
                    case '每半月':
                        $next = date("Y-m-d", strtotime("+15 days", strtotime($lastData['lastDate'])));
                        break;
                    case '每月':
                        $next = date("Y-m-d", strtotime("+1 months", strtotime($lastData['lastDate'])));
                        break;
                    default:
                        $next = $this->date;
                }

                if (self::total(array('table' => 'message', 'where' => " and stid = '$array[stid]' and date(time) = '{$this->date}' and typeId = '{$array['id']}' and type = '预警消息' ")) <= 0) {
                    $equipment = query("equipment", " id = '$array[eqid]' ", "code,name");
                    //给提醒人发消息
                    switch ($array['type']) {
                        case '巡检计划':
                            message(array(
                                'stid' => $array['stid'],
                                'type' => '预警消息',
                                'typeId' => $array['id'],
                                'text' => "设备【{$equipment['code']}-{$equipment['name']}】下次巡检时间为【{$next}】",
                                'targetCla' => 'equipmentInspection',
                                'targetFun' => 'home',
                            ));
                            break;
                        case '保养计划':
                            message(array(
                                'stid' => $array['stid'],
                                'type' => '预警消息',
                                'typeId' => $array['id'],
                                'text' => "设备【{$equipment['code']}-{$equipment['name']}】下次保养时间为【{$next}】",
                                'targetCla' => 'equipmentMaintenance',
                                'targetFun' => 'home',
                            ));
                            break;
                    }
                }
            }
        }
    }

    /**
     *
     * 超期应收预警
     */
    public function overdueReceivableAlert()
    {
        $setting = self::getSettingValue('receivableAlert');
        $result = find(array('table' => 'sale_send_order', 'where' => " settlementType = '月结' and DATEDIFF('{$this->date}',recordDate) > settlementDay and state = '已确认' and isWriteOff = 0 order by recordDate asc "));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                foreach ($setting['member'] as $item) {
                    if (self::total(array('table' => 'message', 'where' => " and stid = '$item' and date(time) = '{$this->date}' and typeId = '{$array['id']}' and type = '预警消息' ")) <= 0) {
                        //给提醒人发消息
                        message(array(
                            'stid' => $item,
                            'type' => '预警消息',
                            'typeId' => $array['id'],
                            'text' => "销售发货单【{$array['orderNo']}】应收已超期",
                            'targetCla' => 'saleSendOrder',
                            'targetFun' => 'detail',
                        ));
                    }
                }
            }
        }
    }

    /**
     *
     * 超期应付预警
     */
    public function overduePayableAlert()
    {
        $setting = self::getSettingValue('payableAlert');
        $result = find(array('table' => 'purchase_get_order', 'where' => " settlementType = '月结' and DATEDIFF('{$this->date}',recordDate) > settlementDay and state = '已确认' and isWriteOff = 0 order by recordDate asc "));
        if (is_array($result['array'])) {
            foreach ($result['array'] as $array) {
                foreach ($setting['member'] as $item) {
                    if (self::total(array('table' => 'message', 'where' => " and stid = '$item' and date(time) = '{$this->date}' and typeId = '{$array['id']}' and type = '预警消息' ")) <= 0) {
                        //给提醒人发消息
                        message(array(
                            'stid' => $item,
                            'type' => '预警消息',
                            'typeId' => $array['id'],
                            'text' => "采购收货单【{$array['orderNo']}】应付已超期",
                            'targetCla' => 'purchaseGetOrder',
                            'targetFun' => 'detail',
                        ));
                    }
                }
            }
        }
    }
}

//
$obj = new doClass();
//echo $obj->echoSql1();
